import React, {useEffect, useRef, useState} from "react";
import style from "./List.module.scss";
import QuestionCard from "../../components/QuestionCard";
import {Empty, Spin, Typography} from "antd";
import ListSearch from "../../components/ListSearch";
import {useSearchParams} from "react-router-dom";
import {useDebounceFn, useRequest} from "ahooks";
import {getQuestionListService} from "../../service/question";
import {LIST_PAGE_SIZE, LIST_SEARCH_PARAMS_KEY} from "../../constants";

const {Title} = Typography;
const List = () => {
  const [list, setList] = useState([]); //列表数据
  const [total, setTotal] = useState(0); //总得数据
  const [page, setpage] = useState(1); //当前页数
  const haveMoreData = total > list.length; //是否还有更多数据
  const [searchParams] = useSearchParams();
  const containRef = useRef<HTMLDivElement>(null);
  const [started, setstarted] = useState(false); //是否是第一次加载
  const keyword = searchParams.get(LIST_SEARCH_PARAMS_KEY);
  //keyword 发生变化时，恢复初始第一页状态
  useEffect(() => {
    setstarted(false);
    setTotal(0);
    setList([]);
    setpage(1);
    return () => {
    };
  }, [keyword]);

  //   加载数据
  const {run: load, loading} = useRequest(async () => {
      const data = await getQuestionListService({
        keyword: searchParams.get(LIST_SEARCH_PARAMS_KEY) || "",
        page,
        pageSize: LIST_PAGE_SIZE,
      });
      return data;
    },
    {
      manual: true,
      onSuccess(result) {
        const {list: l, total} = result;
        console.log("result", result);
        setTotal(total);
        setList(list.concat(l));
        setpage(page + 1);
      },
    }
  );
  // 1.首次加载或者路由改变时加载数据
  const {run: tryLoadMore} = useDebounceFn(() => {
      const elem = containRef.current;
      if (elem === null) return;
      const domRem = elem.getBoundingClientRect();
      if (domRem === null) {
        return;
      }
      const {bottom} = domRem;
      if (bottom <= document.body.clientHeight) {
        load();
        setstarted(true);
      }
    },
    {
      wait: 1000,
    }
  );

  useEffect(() => {
    tryLoadMore();
  }, [searchParams]);
  // 2.判断加载是否还有更多数据,如果存在更多数据，给滚动条加载监听事件
  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener("scroll", tryLoadMore);
    }
    return () => {
      window.removeEventListener("scroll", tryLoadMore);
    };
  }, [searchParams, haveMoreData]);
  //   根据不同情况加载底部样式
  const LoadMoreContentElem = () => {
    if (!started || loading) return <Spin/>;
    if (total === 0) return <Empty description={"暂无数据"}/>;
    if (!haveMoreData) return <span>没有更多了</span>;
    return <span>开始加载下一页</span>;
  };
  return (
    <>
      <div className={style.header}>
        <div className={style.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={style.right}>
          <ListSearch/>
        </div>
      </div>
      <div className={style.content}>
        {list.length > 0 &&
          list.map((item: any) => {
            const {_id} = item;
            return <QuestionCard key={_id} {...item} />;
          })}
      </div>
      <div className={style.footer} ref={containRef}>
        <div>{LoadMoreContentElem()}</div>
      </div>
    </>
  );
};

export default List;
